package org.youyun56.gpsserver.apache.tomcat;

import java.util.HashMap;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.sun.net.httpserver.HttpExchange;

public class HttpRequest {
    private HttpExchange exchange;
    private final static Logger logger = Logger.getLogger(HttpRequest.class);
    private final static String AND = "&";
    private final static String equals = "=";
    private HashMap<String, String> parameters;

    public HttpRequest(HttpExchange exchange) {
        // TODO Auto-generated constructor stub
        this.exchange = exchange;
    }

    public String getParameter(String name) {
        if (parameters == null) {
            parameters = new HashMap<String, String>();
            String query = exchange.getRequestURI().getQuery();
            if (StringUtils.isNotEmpty(query)) {
                String[] kvs = query.split(AND);
                for (int i = 0; i < kvs.length; i++) {
                    String kv[] = kvs[i].split(equals);
                    if (kv.length == 2) {
                        parameters.put(kv[0].trim(), kv[1].trim());
                    }
                }
            }
        }
        return parameters.get(name);
    }

    public Long getLong(String name) {
        return Long.parseLong(getParameter(name));
    }

    public Integer getInt(String name) {
        return Integer.parseInt(getParameter(name));
    }

    public HttpExchange getExchange() {
        return exchange;
    }

    public void setExchange(HttpExchange exchange) {
        this.exchange = exchange;
    }

    public HashMap<String, String> getParameters() {
        return parameters;
    }

    public void setParameters(HashMap<String, String> parameters) {
        this.parameters = parameters;
    }

}
